package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wx
 * Date: 2024-01-04
 * Time: 19:36
 */
public class ThreadDemo24 {

    public static void main(String[] args) {
        //需要一个统一对象进行加锁
        Object locker = new Object();

        Thread t1 = new Thread(() -> {
            synchronized (locker){
                System.out.println("t1 wait 之前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t1 wait 之后");
        });
        Thread t2 = new Thread(() -> {

                try {
                    Thread.sleep(5000);//sleep 写到 synchronized 外边,否则,由于 t1 t2 执行顺序不确定,t2 可能会先拿到锁,此时 t1 没执行到 wait
                                         //t2 就先 notify   先notify虽然不会有副作用,但是wait无法被唤醒,逻辑上有问题
                    synchronized (locker) {
                        System.out.println("T2 notify 之前");
                        locker.notify();
                        System.out.println("T2 notify 之后");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        });
        t1.start(); //t1 启动就会调用wait,进入阻塞等待中
        t2.start(); //t2 启动先sleep sleep时间到了之后,,在进行notify唤醒t1
    }
}
